package top.jnaw.jee.platform.controller.basics.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.Department;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Strings;

public class DepartmentController extends Controller {

  public void add() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final String name = Strings.getString(req, "name", "");
    final int type = Strings.getInt(req, "type", Consts.DEFAULT_BAD_ID);
    if (StrKit.notBlank(name)) {
      result = Department.add(name, type);
    }
    renderJson(result.toJson());
  }

  public void del() {
    ModelResult result = new ModelResult(Result.kModelDeleteError);
    JSONObject req = Strings.toJSONObject(this);
    JSONArray ids = Strings.getJSONArray(req, "ids", null);
    if (null != ids && ids.size() > 0) {
      for (int i = 0; i < ids.size(); i++) {
        if (Department.del(ids.getInteger(i))) {
          result.setResult(Result.kSuccess);
        }
      }
    }
    renderJson(result.toJson());
  }

  public void update() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    final int charge = Strings.getInt(req, "charge", Consts.DEFAULT_BAD_ID);
    final String name = Strings.getString(req, "name", "");
    final int type = Strings.getInt(req, "type", Consts.DEFAULT_BAD_ID);
    if (id > 0) {
      result = Department.update(id, name, type, charge);
    }
    renderJson(result.toJson());
  }

  public void list() {
    JSONObject req = Strings.toJSONObject(this);
    final int page = Strings
        .getInt(req, "page", Consts.DEFAULT_PAGE);
    final int size = Strings
        .getInt(req, "size", Consts.DEFAULT_PAGE_SIZE);
    final JSONArray filter = Strings.getJSONArray(req, "filter", null);
    final JSONArray search = Strings.getJSONArray(req, "search", null);
    if (page > 0) {
      renderJson(Strings
          .formatJsonDateTime(
              Department.list(page, size, filter, search)));
    } else {
      renderJson(Department.list(filter).toJson());
    }
  }


  public void query() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    if (id > 0) {
      result = Department.query(id);
    }
    renderJson(result.toJson());
  }

}
